﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace Ics.NuttxSharp.Bsp.CanFd
{
    using uint32_t = System.UInt32;
    using uint8_t = System.Byte;

    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    public struct FDCAN_RxHeaderTypeDef
    {
        public uint32_t Identifier;
        public uint32_t IdType;
        public uint32_t RxFrameType;
        public uint32_t Dlc;
        public uint32_t ErrorStateIndicator;
        public uint32_t BitRateSwitch;
        public uint32_t FDFormat;
        public uint32_t RxTimestamp;
        public uint32_t FilterIndex;
        public uint32_t IsFilterMatchingFrame;
    }

    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    public struct FDCAN_TxHeaderTypeDef
    {
        public uint32_t Identifier;
        public uint32_t IdType;
        public uint32_t TxFrameType;
        public uint32_t Dlc;
        public uint32_t ErrorStateIndicator;
        public uint32_t BitRateSwitch;
        public uint32_t FDFormat;
        public uint32_t TxEventFifoControl;
        public uint32_t MessageMarker;
    }

    // 与 native 对应的事件类型
    public enum CanFdEventType : int
    {
        CanFdEventType_RxMessage = 0,
        CanFdEventType_Error = 1,
        CanFdEventType_TxComplete = 2,
    }

    // 原生布局：Rx 消息
    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    public unsafe struct CanFdRxMessageNative
    {
        public int CanIndex;
        public FDCAN_RxHeaderTypeDef Header;
        // 固定长度 64 字节负载，与 native 保持一致
        public fixed byte Data[64];
    }

    // 原生布局：Error 消息
    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    public struct CanErrorMessageNative
    {
        public int CanIndex;
        public uint ErrorCode;
    }

    // 原生布局：TxComplete 消息
    [StructLayout(LayoutKind.Sequential, Pack = 4)]
    public struct CanTxCompleteMessageNative
    {
        public int CanIndex;
    }

    // 原生布局：包含枚举 + union（使用 Explicit + FieldOffset 实现 union）
    [StructLayout(LayoutKind.Explicit, Pack = 4)]
    public unsafe struct CanFdEventMessageNative
    {
        [FieldOffset(0)]
        public CanFdEventType EventType;

        // union 从 offset 4 开始（假定枚举为 4 字节）
        [FieldOffset(4)]
        public CanFdRxMessageNative RxMessage;

        [FieldOffset(4)]
        public CanErrorMessageNative ErrorMessage;

        [FieldOffset(4)]
        public CanTxCompleteMessageNative TxCompleteMessage;
    }


    public static unsafe class NativeMethods
    {
        
        // native 导入
        [DllImport("*")]
        public static extern int Hal_Can_GetFdCanCount();

        [DllImport("*")]
        public static extern int Hal_Can_Send(int canIndex, FDCAN_TxHeaderTypeDef* header, uint8_t* txData);

        [DllImport("*")]
        public static extern IntPtr Hal_Can_GetEventQueueHandle(int canIndex);
    }
}
